﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GALibrary.Scheduling
{
    public class ShortestRemainingTime : BaseScheduler
    {
        public ShortestRemainingTime(IScheduling _nextLevelSchedule)
        {
            this.nextLevelSchedule = _nextLevelSchedule;
            this.tasks = new List<Entity.TaskSchedulerGA>();
        }
        public override Entity.TaskSchedulerGA FindUnScheduleTask()
        {
            if ((tasks.Count() >= 1 && this.nextLevelSchedule != null) || (tasks.Count() == 1 && this.nextLevelSchedule == null))
            {
                return this.tasks.OrderByDescending(p => (p.Duration - p.ExecutedDuration)).ThenByDescending(p => p.StartingTime).Select(p => p).FirstOrDefault();
            }
            else
            {
                this.OwnSort();
            }
            return null;
        }

        public override Entity.TaskSchedulerGA GetPeekTasks()
        {
            var tempPeek = this.tasks.OrderBy(p => (p.Duration - p.ExecutedDuration)).ThenBy(p => p.StartingTime).Select(p => p).FirstOrDefault();
            if (tempPeek != null)
            {
                this.tasks.Remove(tempPeek);
                Entity.TaskSchedulerGA temptask;
                if (this.tasks.Count <= 0 && this.nextLevelSchedule != null && (temptask = ((BaseScheduler)this.nextLevelSchedule).GetPeekTasks()) != null)
                {
                    this.tasks.Add(temptask);
                }
                return tempPeek;
            }
            return null;
        }

        public override void OwnSort()
        {
            this.tasks = this.tasks.OrderBy(p => (p.Duration - p.ExecutedDuration)).ThenBy(p => p.StartingTime).ToList();
        }
    }
}
